var router = require('libs/router').router;
var pages = require('libs/pages');
var ItemMixin = require('mixins/item');
var libs = require('libs/libs');
var api = libs.api;
var List = require('modules/list/load_list')(true, 'wCard');
var store = require('mixins/store');
var radio = require('modules/form/radio1')
var chooseWXPay = require('modules/weixin/chooseWXPay');
var Service = require('../_comm/service')



var _ = libs.lodash;
var _getLogin = SA.get('USER');       //获取login值
var _totalprice = 0;
var _numdata = 0;
var _cardData = [];
var _page = {
    onlineInfo: false
}

var bindEvent = function(){
    var postdata = {
        login: SA.get('USER').login,
        method: 'get'
    }
    $('.express').click(function(){
        router('express');
    });
    $('.send').click(function(){
        router('send/send');
    });
    $('.water').click(function(){
        router('water/send');
    });
    $('.userCenter').click(function(){
        SA.set('_GoBack', 'water/card')
        router('uc/index',{'back':'water/card'});
    });
    setTimeout(function(){
        $('#water_card').find('.flex-1').animate({scrollTop: '1000px'}, 1000)
    },500)
    //短信订阅
    $('.subscribe_btn_water').click(function(){
        router('uc/sms',{'back':'water/card'});
    });
    //点击网点介绍
    $('.default_label_branches').click(function(){
        router('uc/siteIntroduce');
    });
    $('.default_foot').show();
    api.req('/card_list', postdata, function(data){
        console.log(data)
        if(data.code == '114000' || data.code == '115000' ){
            router('uc/location')
        }else{
            if(data.length){
                data.map(function(item, i){
                    _cardData.push(
                        <div className="bL-li" key={"_cardata"+i}>
                            <div className="bL_pic"><img src={item.url}/></div>
                            <div className="bL_com">
                                <em data-id={item.siteCardId}>{item.cardName}</em>
                                <p><span className="bL_color">价格：</span><span className="bL_color bL_sellprice">{item.sellPrice}</span><i>原价：{item.originalPrice}</i></p>
                            </div>
                            <div className="bL_num">
                                <div className="bl_no_num">
                                    <i className="iconfont icon-jikediancanicon08 bL_num_minus"></i>
                                    <span>0</span>
                                </div>
                                <i className="iconfont icon-jia bL_num_add"></i>
                            </div>
                        </div>
                    )
                })
            }
            SA.setter('wCard',{data: _cardData});
        }
    })

    var radiodata_waterCard = {
        name: ['微信支付'],
        title: [<span className="pay_icon_bg"><i className="iconfont icon-weixinzhifu"></i>{'微信支付'}</span>],
        value: ['-WEIXIN_DBGZH_PAY']
    }
    var rd_selected = radio(radiodata_waterCard, 'radiodata_waterCard')

    $('#waterCardbtn a').click(function(){
        var wcSum = 0;
        var aa = [];
        $('.waterCardlist li').map(function(){
            wcSum += parseInt($(this).find('.bl_no_num span').html());
            if($(this).find('.bl_no_num span').html()>0){
                aa.push(
                    $(this).find('.bL_com em').attr('data-id')+ '_' +$(this).find('.bl_no_num span').html()
                )
            }
        })
        if(wcSum == 0){
            ui.alertBox({
                cons: [{text:'请选择需要的水卡',name:"bigCon"}],
                btns: [
                ]
            })
        }else{
            if($('#radiodata_waterCard input:checked').val()){
                var payCode_inut = $('#radiodata_waterCard input:checked').val();//获取选中支付方式的值
                var wc_id_num = aa.join(',');//获取水卡的数据并用‘，’分开
                var _loginmsg = SA.get('USER');
                var postdata_buy = {
                    login:_loginmsg.login,
                    siteCardIds: wc_id_num,  //卡券ID数量组合字符串  例如：“abc_1,bcd_2” 表示abc卡1张，bcd卡2张
                    payCode:payCode_inut,
                    method: 'get'
                }
                api.req('/buyWaterCard', postdata_buy, function(data){
                    if(data.orderId){
                        var _data = JSON.parse(data.orderId);
                        onBridgeReady(_data);
                        function onBridgeReady(datajson){
            			    WeixinJSBridge.invoke(
        				        'getBrandWCPayRequest', {
        				            "appId" : datajson.appId,     //公众号名称，由商户传入
        				            "timeStamp":datajson.timeStamp,         //时间戳，自1970年以来的秒数
        				            "nonceStr" : datajson.nonceStr, //随机串
        				            "package" : datajson.packageValue,
        				            "signType" : datajson.signType,         //微信签名方式：
        				            "paySign" : datajson.sign //微信签名
        				        },
            			        function(res){
            			            if(res.err_msg == "get_brand_wcpay_request:ok" ) {
            			            	//支付成功后执行
            			            	router('water/send');
            			            }else if(res.err_msg == "get_brand_wcpay_request:cancel" ){
            			            	//取消支付，什么都不做
            				        }else if(res.err_msg == "get_brand_wcpay_request:fail" ){
            			            	//支付失败
                                        alert(JSON.stringify(res));
            			            	alert("支付失败!");
            				        }else{
                                        alert(JSON.stringify(res));
            			            }
            			        }
            			    );
            			};
                    }
                    else if(data.code == '100000001'){
                        ui.alertBox({
                            // cons: [{text:data.message,name:"smallCon"}],
                            cons: [{text:'订单支付成功',name:"bigCon"}],
                            btns: [
                                {
                                    text: '预约送水',
                                    close: true,
                                    callback: function () {
                                        router('water/send')
                                    }
                                },
                                {
                                    text: '返回首页',
                                    close: true,
                                    callback: function () {
                                        if (wx){
                                            wx.closeWindow()
                                        }
                                    }
                                }
                            ]
                        })
                    }
                    else{
                        ui.alertBox({
                            cons: [{text:'提交失败，请重试',name:"bigCon"}],
                            btns: [
                            ]
                        })
                    }
                });
            }
            else{
                ui.alertBox({
                    cons: [{text:'请选择支付方式',name:"bigCon"}],
                    btns: [
                    ]
                })
            }
        }
    })
}

function chageNum(){
    var nowValue = $(this).find('.bl_no_num span');
    var sigerprice = $(this).find('.bL_sellprice').html();
    if(parseInt(nowValue.html())<= 0){
        $(this).find('.bl_no_num').addClass('u-none');
    }else{
        $(this).find('.bl_no_num').removeClass('u-none');
    }
    $(this).find('.bL_num_add').click(function(){
        _this = $(this);
        num_add(_this, nowValue, sigerprice);
    })
    $(this).find('.bL_num_minus').click(function(){
        num_minus($(this), nowValue, sigerprice);
    })
    // 数量+事件
    function num_add(ele, value, price){

        ele.prev('.bl_no_num').removeClass('u-none')
        value.html(parseInt(value.html()) + 1)
        _totalprice = parseFloat(_totalprice) + parseFloat(price);
        SA.setter('_WaterCard', {totalprice: _totalprice.toFixed(2)})
    }
    // 数量-事件
    function num_minus(ele, value, price){
        value.html(parseInt(value.html()) - 1)
        if(parseInt(value.html()) <= 0){
            value.html() == 0;
            ele.parent('.bl_no_num').addClass('u-none')
        }
        _totalprice = _.round(_totalprice,2) - parseFloat(price);
        SA.setter('_WaterCard', {totalprice: _totalprice.toFixed(2)})
    }

}

var WaterCardFooter = React.createClass({
    mixins: [ItemMixin, store('_WaterCard')],
    getInitialState: function(){
		return {
            totalprice: _totalprice
		}
	},
    render: function(){
        return(
            <div>
                <div className="waterCardFooter">
                    <div className="default_pay">
                        <div id="radiodata_waterCard" className="pay_radio"></div>
                    </div>
                </div>
                <div className="default_foot">
                    <div className="dF_total">
                        <p>合计：<i>￥<span className="dF_total_n">{this.state.totalprice}</span></i></p>
                    </div>
                    <div className="dF_btn" id="waterCardbtn">
                        <a>去结算</a>
                    </div>
                </div>
            </div>
        )
    }
})
var WaterCard = React.createClass({
    mixins: [ItemMixin],
    getInitialState: function(){
		return {
            CardlistData: []
		}
	},
    componentWillMount: function(){
        if(this.props.data){
            this.setState({
                CardlistData : this.props.data
            })
        }
        if(this.props.info){
            this.setState({
                CardlistInfo : this.props.info
            })
        }
    },
    render: function(){
        // var dCydata = this.showonlineWillMount()
        var onlineStatus;
        if( SA.get('USER').info.isReceiveSms == true){
            onlineStatus = '短信已订阅'
        }else{
            onlineStatus = '短信订阅'
        }
        return(
            <div id="waterCard" className='expressWarp flex flex-v'>
                <div className="flex-1 f-oTouch">
                    <div className="nav box-shadow">
                        <div className="express">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/express.png" alt="" />
                                </div>
                                <div className="nav-text"><span>我要收件</span></div>
                            </a>
                        </div>
                        <div className="send">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/send.png" alt="" />
                                </div>
                                <div className="nav-text"><span>快递寄件</span></div>
                            </a>
                        </div>
                        <div className="water">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/water.png" alt="" />
                                </div>
                                <div className="nav-text"><span>预约送水</span></div>
                            </a>
                        </div>
                        <div className="waterCard">
                            <a href="javascript:;" className="active">
                                <div className="nav-icon">
                                    <img src="/images/waterCard.png" alt="" />
                                </div>
                                <div className="nav-text"><span>购买水卡</span></div>
                            </a>
                        </div>
                    </div>
                    <div className="u-mt-15 box-shadow app_index userCenter">
                        <ul className="default_Picture">
                            <li className="uc_coupon">
                                <div>
                                    <img src="/images/icon-user_03.png" alt=""  className="userImg"/>
                                </div>
                                <label className="userTit">个人中心</label>
                                <i className="iconfont icon-xiangyou"></i>
                            </li>
                        </ul>
                    </div>
                    <div className="mT01 default_pd016 default_community box-shadow">
                        <h3>社区便民</h3>
                        <ul>
                            <Service data={this.state.CardlistInfo}/>
                            <li className="dCy_notice">
                                <div className="dCy_pic">
                                    <img src="/images/img_tu2.png" alt="" />
                                </div>
                                <div className="dCy_b_com">
                                    <div className="dCy_n_com">
                                        <em>小区公告</em>
                                        <p>左邻右里最新动态信息</p>
                                    </div>
                                    <div className="f_submit">
                                        <a className="f_btn subscribe_btn subscribe_btn_water"><i className="iconfont icon-975shoujitongxinlu"></i>{onlineStatus}</a>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div className='flex-1 waterMar box-shadow'>
                        <List data={this.state.CardlistData} listClass={'buyList waterCardlist'} itemMethod={chageNum}/>
                    </div>
                    <WaterCardFooter itemDefaultMethod={bindEvent} />
                </div>
            </div>
        )
    }
})

function start(name){
    return pages.new({
        boot: function(){

        },
        goback: function(){
            // router.cb = function(){
            //     if (wx){
            //         wx.closeWindow()
            //     }
            // }
            var _pre = router.pre();
            if (_pre && _pre.hash==='login'){
                router.cb=function(){
                    if (wx){
                        wx.closeWindow()
                    }
                }
            }
            else {
                router.cb=function(){
                    router.goback()
                }
            }
        },
        trigger: function(){
            _this = this;
            api.req('/onlineInfo',{login: SA.get('USER').login, method:'get'}, function(info){
                if(!info.code){
                    _page.onlineInfo = true;
                    api.req('/waterHtmlData',{login: SA.get('USER').login, method:'get'}, function(data){
                        console.log(data);
                        if(data.code == '114000' || data.code == '115000'){
                            router('uc/location')
                        }else{
                            pageData = data;
                            _this.main(_this, data, info);
                        }
                    })
                }
            })
            this.libs.changeTitle('购买水卡');
        },
        main: function(self, data, info){
            this.render(
                <WaterCard data={_cardData} info={info}/>,
                document.getElementById(name)
            )
        },
        end: function(){
            _cardData = []
            React.unmountComponentAtNode(document.getElementById(name))
        }
    })
}


module.exports = start;
